package com.assignwork.service.impl;

import com.assignwork.dto.VoyageVisaSearchDTO;
import com.assignwork.dto.VoyageVisaSubmitDTO;
import com.assignwork.entity.VoyageVisa;
import com.assignwork.mapper.VoyageVisaMapper;
import com.assignwork.service.ICommonService;
import com.assignwork.service.ICorpCargoService;
import com.assignwork.service.IShipAgentService;
import com.assignwork.service.IVoyageVisaService;
import com.assignwork.vo.VoyageVisaPageVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.system.cache.DictBizCache;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 船舶签证实现类
 */
@Service
@AllArgsConstructor
public class VoyageVisaServiceImpl extends BaseServiceImpl<VoyageVisaMapper, VoyageVisa> implements IVoyageVisaService {
    private ICommonService commonService;

    @Override
    public IPage<VoyageVisaPageVO> selectVoyageVisaPage(VoyageVisaSearchDTO dto, IPage<VoyageVisaPageVO> page) {
        List<VoyageVisaPageVO> data = baseMapper.selectVoyageVisaList(dto, page);
        if (!Func.isNull(data) && !data.isEmpty()) {
            for (VoyageVisaPageVO vo : data) {
                if (!Func.isNull(vo.getPackageBulkKey())) {
                    vo.setPackageBulkName(DictBizCache.getValue("package_bulk", vo.getPackageBulkKey()));
                }
                if (!Func.isNull(vo.getCreateUser())) {
                    vo.setCreateUserName(commonService.userName(vo.getCreateUser().toString()));
                }
                if (!Func.isNull(vo.getUpdateUser())) {
                    vo.setUpdateUserName(commonService.userName(vo.getUpdateUser().toString()));
                }
            }
        }

        return page.setRecords(data);
    }

    @Override
    public Boolean submitVoyageVisa(VoyageVisaSubmitDTO dto) {
        VoyageVisa entity = BeanUtil.copy(dto, VoyageVisa.class);
        return super.saveOrUpdate(entity);
    }

    @Override
    public BigDecimal visaTonByVoyageId(String voyageId) {
        QueryWrapper<VoyageVisa> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(VoyageVisa::getVisaTon).eq(VoyageVisa::getIsDeleted, 0).eq(VoyageVisa::getVoyageId, Func.toLong(voyageId));
        List<VoyageVisa> tons = baseMapper.selectList(queryWrapper);

        BigDecimal allViseTon = new BigDecimal(0);
        if (!Func.isNull(tons) && !tons.isEmpty()) {
            for (VoyageVisa ton : tons) {
                allViseTon = allViseTon.add(ton.getVisaTon());
            }
        }

        return allViseTon;
    }
}